package service

import (
	"crypto/md5"
	"electron/version/update/utils"
	"fmt"
	"io"
	"os"

	"github.com/spf13/viper"
)

func Version(VersionMd5 string) (bool, string) {
	// 读取文件内容，生成MD5值
	dir, _ := os.Getwd()
	file, _ := os.Open(dir + "/version.conf")
	defer file.Close()
	wr, _ := io.ReadAll(file)

	hash := md5.New()
	hash.Write(wr)
	hashStr := hash.Sum(nil)
	md5str1 := fmt.Sprintf("%x", hashStr) //将[]byte转成16进制
	if md5str1 == VersionMd5 {
		return true, ""
	} else {
		return false, string(wr)
	}
}

func UpdateVersion() ([]string, error) {
	//  用户选择更新版本，请求oss后端存储数据，更新本地文件
	client, err := utils.OssClient.Bucket(viper.GetString("oss.bucketName"))
	if err != nil {
		fmt.Println("Error:", err)
		return nil, err
	} else {
		// 下载文件到流。
		list, err := client.ListObjects()
		if err != nil {
			fmt.Println("Error:", err)
			return nil, err
		} else {
			tmp := []string{}
			for _, object := range list.Objects {
	
				tmp = append(tmp, viper.GetString("oss.DomainName")+object.Key)
			}
			return tmp, nil
		}
	}
}
